<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true"  v-show="showSearch" :rules="rules" label-width="72px">
                     <el-form-item label="日期" prop="dataTime" label-width="40px">
                        <WeekTimePicker type="datetime" v-model="queryParams.createTime" format="yyyy-MM-dd HH:mm" :clearable="false" style="width: 160px"/>
                        <span style="margin: 0px 6px;">~</span>
                        <WeekTimePicker type="datetime" v-model="queryParams.endTime" format="yyyy-MM-dd HH:mm" :clearable="false" style="width: 160px" />
                      </el-form-item>
                      <el-form-item label="制造区域" prop="factoryAreaId">
                            <el-select v-model="queryParams.factoryAreaId" placeholder="区域" clearable @change="areaChange" style="width: 90px">
                                <el-option
                                        v-for="dict in factoryAreaIdOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="制造类型" prop="productionTypeId">
                            <el-select v-model="queryParams.productionTypeId" placeholder="制造类型" clearable @change="productionTypeIdChange" style="width: 90px">
                                <el-option
                                        v-for="dict in listProductionTypeOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="主线ID" prop="machineGroup">
                            <el-select v-model="queryParams.machineGroup" placeholder="主线ID" clearable  style="width: 120px">
                                <el-option
                                        v-for="dict in listMachineGroupOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="设备号" prop="eqpId">
                            <el-input v-model="queryParams.machineId" placeholder="设备号模糊匹配" clearable style="width: 100px;" @keyup.enter="handleQuery" />
                        </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">

            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['PRDMonitor:traceInfo:export']"
                >导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <t-ag-grid
          :style="{height: height}"
          :column-defs="column"
          :row-data="traceInfoList"
          :row-buffer="20"
          row-selection="multiple"
          :suppress-row-click-selection="true"
          :row-multi-select-with-click="true"
          align="center"
          header-align="center"
          :defaultColDef = "{
              menuTabs: ['filterMenuTab', 'columnsMenuTab']
          }"
          @selection-changed="selectionChanged"
          />

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

    </div>
</template>

<script setup name="TraceInfo">
  import { listTraceInfo } from "@/api/PRDMonitor/traceInfo"
  import { factoryAreaIdOptions, listMachineTypeOptions } from '@/common/options'
  import { getMachineTypeId, getModelType, getEqpTypeId } from '@/common/affect'
  import moment from 'moment'
  import request from '@/utils/request'

  const { proxy } = getCurrentInstance()
  const { oee_b_machine } = proxy.useDict('oee_b_machine')

  const traceInfoList = ref([])
  const listMachineGroupOptions = ref([])
  const listProductionTypeOptions = ref([])
  const open = ref(false)
  const loading = ref(true)
  const showSearch = ref(true)
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const total = ref(0)
  const title = ref("")

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10000,
      createTime: moment().subtract(1, 'days').format('YYYY-MM-DD 08:30:00'),
      endTime: moment().format('YYYY-MM-DD 08:30:00'),
      factoryAreaId: '层前',
      productionTypeId: '叠瓦',
      machineGroup: 'H05-DWHJ01',
      machineId: null,
      topId: null,
      machineId: null
    },
    rules: {
      factoryAreaId: [{ required: true, message: "制造区域不能为空", trigger: "change" }],
      productionTypeId: [{ required: true, message: "制造类型不能为空", trigger: "change" }],
      machineGroup: [{ required: true, message: "主线ID不能为空", trigger: "change" }]
    }
  })

  const { queryParams, form, rules } = toRefs(data)

  const height = ref('calc(100% - 100px)')

  const column = [
    { headerName: "设备组", field: "machineGroup", minWidth: 120, flex: 1 },
    { headerName: "上级设备", field: "topId", minWidth: 100, flex: 1 },
    { headerName: "设备号", field: "machineId", minWidth: 120, flex: 1 },
    { headerName: "数量", field: "wipCount", minWidth: 60, flex: 1 },
    { headerName: "Cell数量", field: "cellCount", minWidth: 80, flex: 1 },
    { headerName: "单位", field: "unit", minWidth: 70, flex: 1 },
    { headerName: "在制ID", field: "doingId", minWidth: 200, flex: 1 },
    { headerName: "开始时间", field: "createTime", minWidth: 150, flex: 1 },
    { headerName: "结束时间", field: "endTime", minWidth: 150, flex: 1 },
    { headerName: "持续时长", field: "keepTime", minWidth: 80, flex: 1 },
    { headerName: "Start TT", field: "startTt2", minWidth: 100, flex: 1 },
    { headerName: "End TT", field: "endTt2", minWidth: 100, flex: 1 },
    { headerName: "产品信息", field: "productId", minWidth: 120, flex: 1 },
    { headerName: "加工工艺", field: "workmanship", minWidth: 120, flex: 1 },
    { headerName: "Rcode", field: "rcode", minWidth: 120, flex: 1 },
    { headerName: "硬件状态", field: "hardwareStatus", minWidth: 120, flex: 1 }
  ]

  column.forEach((item) => {
    item.filter = 'agMultiColumnFilter'
  })

  const gridApi = ref()

  const selectionChanged  = (params) => {
    gridApi.value = params.api
    const selectedRows = params.api.getSelectedRows()
    single.value = selectedRows.length !== 1
    multiple.value = !selectedRows.length
  }

  const getgetMachineTypeIdListInfo = (productionTypeId) => {
    return request({
      url: '/parameter/getMachineGroupByMachineTypeId/?machineType=' + productionTypeId,
      method: 'get'
    })
  }

  const areaChange = (target, flag) => {
    if(flag !== 'cls'){
      queryParams.value.productionTypeId = null
    }
    queryParams.value.machineId = null
    listProductionTypeOptions.value = []
    if(!target.length) return
    getModelType({
      factoryAreaIdList: target
    }).then((res) => {

      res.rows.forEach(item => {
        listProductionTypeOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }

  const productionTypeIdChange = (target, flag) => {
    if(flag !== 'cls'){
      queryParams.value.machineGroup = null
    }
    queryParams.value.machineId = null
    listMachineGroupOptions.value = []
    if(!target.length) return
    getgetMachineTypeIdListInfo(
      queryParams.value.productionTypeId
    ).then((res) => {
      res.rows.forEach(item => {
        listMachineGroupOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }

  function getList() {
    if(moment(queryParams.value.endTime).subtract(3, 'days')>moment(queryParams.value.createTime)){
      proxy.$modal.alertWarning('最多查询3天数据')
      return
    }
    loading.value = true
    queryParams.value.createTime = moment(queryParams.value.createTime).format('YYYY-MM-DD HH:mm:ss')
    queryParams.value.endTime = moment(queryParams.value.endTime).format('YYYY-MM-DD HH:mm:ss')
    listTraceInfo(queryParams.value).then(response => {
      traceInfoList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  }

  function cancel() {
    open.value = false
    reset()
  }

  function reset() {
    form.value = {
      id: null,
      createTime: null,
      topId: [],
      machineId: [],
      doingId: null,
      wipCount: null,
      cellCount: null,
      unit: null,
      endTime: null,
      keepTime: null,
      startTt: null,
      endTt: null,
      productId: null,
      machineGroup: null,
      workmanship: null,
      startTt2: null,
      endTt2: null
    }
    proxy.resetForm("traceInfoRef")
  }

  function handleQuery() {
    console.log(data.queryParams)
    proxy.$refs.queryRef.validate(valid => { // 表单校验
      if (valid) {
        queryParams.value.pageNum = 1
        getList()
      }
    })
  }

  function resetQuery() {
    proxy.resetForm("queryRef")
    handleQuery()
  }5

  function handleExport() {
    proxy.download('PRDMonitor/traceInfo/export', {
      ...queryParams.value
    }, `traceInfo_${new Date().getTime()}.xlsx`)
  }

  getList()
  areaChange('层前', 'cls')
  productionTypeIdChange('叠瓦', 'cls')
</script>
